package ink.metoo.auto.fishpi.chatroom.command

import ink.metoo.auto.fishpi.Log
import ink.metoo.auto.fishpi.Settings
import ink.metoo.auto.fishpi.call.ChatRoomCall
import ink.metoo.auto.fishpi.call.UserCall
import ink.metoo.auto.fishpi.chatroom.Message
import org.apache.commons.collections4.map.PassiveExpiringMap
import org.apache.commons.lang3.math.NumberUtils
import java.util.concurrent.TimeUnit

class SendChequeCommand : Command {

    companion object {

        private val expiringTime = TimeUnit.MINUTES.toMillis(30)
        private val expiringMap =
            PassiveExpiringMap(PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<String, Int>(expiringTime))

    }


    override val commandText: String
        get() = "/支票"

    override fun isMatch(message: Message): Boolean {
        return super.isMatch(message) && message.isMe
    }

    override fun execute(message: Message) {
        val params = message.commandParams
        val name = params.getOrNull(1) ?: return
        val money = NumberUtils.toInt(params.getOrNull(2), 32)
        expiringMap.merge(name, money) { old, new -> old + new }
        ChatRoomCall.sendMessage(
            """
                ### 【支票】 ${Settings.fishpiClient.username} : **$money** 积分
                
                @${name} 请回复任意字符对于本条消息或者直接输入`/兑换支票` 即可获得
                
                ---
                
                > 支票只有30分钟有效, 请及时PY.
            """.trimIndent()
        )
    }


    class SendGetChequeCommand : Command {

        override val commandText: String = "/兑换支票"

        override val commandTypes: Array<Command.Type> = arrayOf(Command.Type.OTHER_CLIENT)

        override fun isMatch(message: Message): Boolean {
            return message.md?.contains(commandText) ?: false
        }

        override fun execute(message: Message) {
            val userName = message.userName

            if (!expiringMap.containsKey(userName)) {
                return
            }
            val money = expiringMap[userName]!!
            val result =
                UserCall.transfer(userName!!, money, "${Settings.fishpiClient.username}的${money}支票积分")
            if (result.code != 0) {
                Log.debug("向${userName}转账失败: ${result.msg}")
                return
            }
            expiringMap.remove(userName)
        }

    }
}